package cn.onein.edu.web.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.onein.edu.biz.bean.User;
import cn.onein.edu.biz.bean.UserTemp;
import cn.onein.edu.common.SexType;
import cn.onein.edu.util.StringUtil;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.jms.producer.SendMailProducer;
import cn.onein.edu.web.service.LearnService;
import cn.onein.edu.web.service.UserService;
import cn.onein.edu.web.util.AjaxCallBackJsonUtil;
import cn.onein.edu.web.util.CenterHotContentUtil;
import cn.onein.edu.web.vo.AjaxCallbackVO;

/**
 * 用户个人信息控制器
 * @author justin
 *
 */
@Controller
public class UserInfoController extends BaseController {

	Logger logger = Logger.getLogger(UserInfoController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SendMailProducer sendMailProducer;
	
	@Autowired
	private LearnService learnService;

	
	/**
	 * 保存成长日志
	 * 
	 * @return
	 */
	@RequestMapping(value = "/center/userinfo", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView index(HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		
		Map<String,Object> param = new HashMap<String,Object>();
		
		User user = this.getLoginUser(req);
		if(null == user){
			return new ModelAndView("error",param);
		}
		
		//得到用户中心最新资讯文章
		CenterHotContentUtil.initHotContent(req, user, learnService, param);
		
		param.put("user", user);
		
		setMenu(param, MENU_VALUE_USER_INFO);
		
		return new ModelAndView("center/userinfo",param);
	}
	
	/**
	 * 验证邮箱是否存在
	 * 
	 * @return
	 */
	@RequestMapping(value = "/service/validateEmail.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void validateEmail(String email,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		
		User user = this.getLoginUser(req);

		if(user.getEmail().equals(email.trim())){
			return;
		}
		
		if(userService.getEmail(email.trim())){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_EXIST_KEY), resp);
		}else{
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_NOTEXIST_KEY), resp);
		}
		
	}
	
	/**
	 * 验证登录名是否存在
	 * 
	 * @return
	 */
	@RequestMapping(value = "/service/validateName.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void validateName(String name,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		
		User user = this.getLoginUser(req);
		
		if(user.getName().equals(name.trim())){
			return;
		}
		
		if(userService.getUserByName(name.trim()) != null){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_EXIST_KEY), resp);
		}else{
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_NOTEXIST_KEY), resp);
		}
	}
	
	/**
	 * 验证密码是否正确
	 * 
	 * @return
	 */
	@RequestMapping(value = "/service/validatePassword.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void validatePassword(String password,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		
		User user = this.getLoginUser(req);
		
		if(null == password || "".equals(password)){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_WRONG_KEY), resp);
			return;
		}
		
		String encodePassword = StringUtil.string2MD5(password);
		
		if(user.getPassword().equals(encodePassword)){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_RIGHT_KEY), resp);
		}else{
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_WRONG_KEY), resp);
		}
	}
	
	/**
	 * 修改用户信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/service/updateUserInfo.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void updateUser(User updateUser,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		User loginUser = this.getLoginUser(req);
		UserTemp userTemp = null;
		
		if(null == updateUser || "".equals(updateUser.getName().trim()) || "".equals(updateUser.getEmail().trim())){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
		}
		
		try{
			updateUser.setNickName(URLDecoder.decode(updateUser.getNickName(),"UTF-8")) ;
			updateUser.setName(URLDecoder.decode(updateUser.getName(),"UTF-8")) ;
			updateUser.setEmail(URLDecoder.decode(updateUser.getEmail(),"UTF-8")) ;
			updateUser.setId(loginUser.getId());
			
			if(!loginUser.getEmail().trim().equals(updateUser.getEmail().trim())){
				userTemp = new UserTemp();
				userTemp.setEmail(updateUser.getEmail());
				userTemp.setUserId(loginUser.getId());
				userTemp.setUuid(StringUtil.getNewUUID());
			}
			
			userService.updateUser(updateUser, userTemp);
			
			if(!loginUser.getEmail().trim().equals(updateUser.getEmail().trim())){
				String changeEmailUrl = req.getRequestURL().toString().replace("service/updateUserInfo.json", "activeNewEmail/" + userTemp.getUuid() + ".jhtml");
				sendMailProducer.sendChangeEMailUrlMessage(updateUser.getEmail(), changeEmailUrl);
			}
			
			User userBean = userService.getUserById(loginUser.getId());
			req.getSession(true).setAttribute(SESSION_USER_KEY, userBean);
		}catch(Exception e){
			logger.error("update user info error.",e);
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
		}
		
		AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXSUCCESS), resp);
	}
	
	/**
	 * 确认修改邮箱
	 * 
	 * @return
	 */
	@RequestMapping(value = "/activeNewEmail/{uuid}.jhtml", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView confirmEail(@PathVariable String uuid,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		Map<String,Object> param = new HashMap<String,Object>(); 
		
		if(null == uuid || "".equals(uuid)){
			return new ModelAndView("error");
		}
		
		try{
			UserTemp user = userService.getUserTempByUUID(uuid);
			if(null == user){
				return new ModelAndView("resourceNotFound");
			}
			param.put("user", user);
		}catch(Exception e){
			logger.error("confirm email error.", e);
			return new ModelAndView("error");
		}
		
		setMenu(param, MENU_VALUE_ACTIVE_NEW_EMAIL);
		
		return new ModelAndView("center/activeemail",param);
	}
	
	/**
	 * 激活新邮箱
	 * 
	 * @return
	 */
	@RequestMapping(value = "/active/doActiveNewEmail.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void doActiveEmail(String password,String uuid,String email,Long userId,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		
		if(null == uuid || "".equals(uuid) || null == userId || null == email || "".equals(email)){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
			return;
		}
		
		try{
			User user = userService.getUserById(userId);
			if(user == null || !user.getPassword().equals(StringUtil.string2MD5(password))){
				AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
				return;
			}
			
			userService.updateUserEmailByUserId(uuid,email,userId);
		}catch(Exception e){
			logger.error("do active email error.", e);
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
			return;
		}
		
		AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXSUCCESS), resp);
	}
	
	/**
	 * 修改用户密码
	 * 
	 * @return
	 */
	@RequestMapping(value = "/service/updatePassword.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void updateUser(String newpassword,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		User loginUser = this.getLoginUser(req);
		
		if(null == newpassword || "".equals(newpassword)){
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
		}
		
		try{
			String encodePassword = StringUtil.string2MD5(newpassword);
			userService.updateUserPassword(loginUser.getId(), encodePassword);
			User userBean = userService.getUserById(loginUser.getId());
			req.getSession(true).setAttribute(SESSION_USER_KEY, userBean);
		}catch(Exception e){
			logger.error("update password error in updateUserPaassword function.", e);
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
		}
		
		AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXSUCCESS), resp);
	}
	
	/**
	 * 修改用户扩展信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/service/updateExtend.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void updateUserExtend(User user,String sexTemp,String parentSexTemp,HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		User oldUser = this.getLoginUser(req);
		
		if(null != sexTemp || !"".equals(sexTemp)){
			if ("0".equals(sexTemp)) {
				user.setSex(SexType.F);
			}
			if ("1".equals(sexTemp)) {
				user.setSex(SexType.M);
			}
		}
		
		if(null != parentSexTemp || !"".equals(parentSexTemp)){
			if ("0".equals(parentSexTemp)) {
				user.setParentSex(SexType.F);
			}
			if ("1".equals(parentSexTemp)) {
				user.setParentSex(SexType.M);
			}
		}
		
		try{
			user.setId(oldUser.getId());
			userService.updateUserExtendInfo(user,oldUser);
			User userBean = userService.getUserById(oldUser.getId());
			req.getSession(true).setAttribute(SESSION_USER_KEY, userBean);
		}catch(Exception e){
			logger.error("update user extend error in updateUserExtend function.", e);
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR), resp);
		}
		
		AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXSUCCESS), resp);
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
		
	}
	
}
